var dataSource = function(pSection, pRoot){
	
	var jLoader = Ti.Network.createHTTPClient();
	
	if(pSection == 'weibo'){
		jLoader.onload = function(e) {
			if (jLoader.status == 200){
				
				var jData = JSON.parse(jLoader.responseData);
				if(pRoot.id == 'dView'){
					pRoot.top = 55;
					pRoot.data = weiData(pRoot, jData);
					loadWin.close();
					
				}else{
					weiboData(pRoot, jData[0]);
					loadWin.close();
				}
				saveData(rawData, 'sina.js');
				
			}
		}
		
		if(checkNetwork()){
			jLoader.open('GET', 'http://api.t.sina.com.cn/statuses/user_timeline/1963017723.json?source=2424068513');
			jLoader.send();
			loadWin.open();
		}
		
		
	}else{
		
		onData(pSection, pRoot, offData());
		
	}

}


var rtData = function(pId, pRT){
	var jLoader = Ti.Network.createHTTPClient();	
		jLoader.onload = function(e) {
			if (jLoader.status == 200) {
				RT = JSON.parse(jLoader.responseData)[0];
				rtText = "评论:"+RT.rt+" | 转发:"+RT.comments;
				pRT.text = rtText;
				
			}else{
				errorMSG("远程服务器无法响应，请稍后再试。");
				
			}
		};
		jLoader.open('GET', 'http://api.t.sina.com.cn/statuses/counts.json?source=2424068513&ids='+pId);
		jLoader.send();
}


var getCorrectFile = function(pFile){
	

	var remoteFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, pFile);
	if(remoteFile.exists()){
		localPath = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, '').nativePath+pFile;
	}else{
		localPath = pFile;
	}
	
	//Ti.API.debug(pFile);
	//Ti.API.debug(localPath);
	
	return localPath;
}

var homeList = function(pRoot, jHome){
	var dTable = [];
	var jMenu = [];
	
	for(var k in jHome){
		var rowData = Titanium.UI.createTableViewRow({
			height: 70
		});
		var mNews = Ti.UI.createImageView({
			image: getCorrectFile(jHome[k].img + "1.png"),
			width: 320,
			height: 70,
		});
		rowData.add(mNews);
		dTable.push(rowData);
		jMenu.push(k);
		
	}
	
	pRoot.addEventListener('click', function(e){
		
		if(jHome[jMenu[e.index]].content.img){
			Ti.include('detail.js');
			var wDe = new wDetail();
			wDe.dNews('magic', jHome[jMenu[e.index]].content);
		}else{
			Ti.include('home.js');
			tW = tmpWin(jMenu[e.index], jHome[jMenu[e.index]].content);
			tW.open();
		}
		
	});
	
	
	return dTable;
}

var videoList = function(pRoot, jsonData){
	var dTable = [];
	
	for(var k in jsonData){
		var rowData = Titanium.UI.createTableViewRow();
		var mNews = Ti.UI.createImageView({
			image:  getCorrectFile(jsonData[k].img + "1.png"),
			width: 320,
			height: 59,
		});
		if(k == 0){
			rowData.height = 186;
			mNews.height = 186;
		}else{
			rowData.height = 60;
			rowData.backgroundImage = "media/images/line.png";
			mNews.height = 59;
		}
		rowData.add(mNews);
		dTable.push(rowData);
	}
	
	pRoot.addEventListener('click', function(e){
		var pURL = jsonData[e.index].vod;
		Ti.API.debug(pURL);
		
		var activeMovie = Ti.Media.createVideoPlayer({
			url: pURL,
			fullscreen: true
		});
		var winVideo = Titanium.UI.createWindow({
			backgroundColor: 'transparent'
		});
		
		if(checkNetwork()){
			winVideo.add(activeMovie);
			winVideo.open();
			winVideo.orientationModes = [Ti.UI.LANDSCAPE_RIGHT];
			activeMovie.play();	
		}
						
		activeMovie.addEventListener('swipe',function(e){
			activeMovie.stop();
			winVideo.close();
		});
		activeMovie.addEventListener('complete',function(e){
			winVideo.close();
		});
		activeMovie.addEventListener('click',function(e){
			activeMovie.stop();
			winVideo.close();
		});
	
	});
	
	return dTable;
}

var weiData = function(pRoot, jsonData){
	var jL = jsonData.length;
	var dTable = [];
	
	for (var i = 0; i < jL; i++){
		var rowData = Titanium.UI.createTableViewRow({
			backgroundColor: "white",
		});
		var weiView = Titanium.UI.createView({
			width: 320,
		});
		var weiboCreated = new Date(jsonData[i].created_at);
		var wC = weiboCreated.getMonth()+"月"+weiboCreated.getDate()+"日 "+weiboCreated.getHours()+":"+weiboCreated.getMinutes();
		
		var weiTimeText = Titanium.UI.createLabel({
			top: 0,
			height: 12,
			right: 20,
			width: 100,
			text: wC,
			font: {fontSize: 10},
			textAlign: 'right',
		})
		var weiTimeIcon = Titanium.UI.createImageView({
			image: "media/weibo/time.png",
			width: 13,
			height: 12,
			top: 0,
			right: weiTimeText.right+weiTimeText.width,
		})
		weiView.add(weiTimeText);
		weiView.add(weiTimeIcon);
		
		var weiText = Titanium.UI.createLabel({
			top: weiTimeIcon.height,
			height: 40,
			left: 20,
			width: 280,
			text: jsonData[i].text,
			font: {fontSize: 14},
		})
		weiView.add(weiText);
		
		weiView.height = weiTimeIcon.height + weiText.height;
		
		var weiRT = Titanium.UI.createLabel({
			top: weiTimeIcon.height + weiText.height,
			height: 12,
			right: 20,
			font: {fontSize: 10},
			width: 280,
			textAlign: 'right',
		})
		weiView.add(weiRT);
		rtData(jsonData[i].id, weiRT);
		
		if(jsonData[i].thumbnail_pic){
			var weiThumb = Titanium.UI.createImageView({
				image: jsonData[i].thumbnail_pic,
				top: weiView.height,
				height: 64,
				width: 64,
				left: 20,
			})
			weiView.add(weiThumb);
			weiRT.top = weiView.height + weiThumb.height;
			weiView.height = weiView.height + weiThumb.height;
		}
		
		var weiLine = Titanium.UI.createImageView({
			image: "media/weibo/line.png",
			width: 320,
			height: 1,
			bottom: 2,
		});
		weiView.add(weiLine);
		
		weiView.height = weiView.height + weiRT.height + weiLine.height + 5;
		
		rowData.height = weiView.height + 10;
		
		rowData.add(weiView);
		dTable.push(rowData);
		
	}
	
	pRoot.addEventListener('click', function(e){
		Ti.include('detail.js');
		var wDe = new wDetail();
		var pWeibo = jsonData[e.index];
		wDe.dWeibo(pWeibo);
	})
	
	return dTable;
}


var weiboData = function(pRoot, jsonData){

	var vFollower = Titanium.UI.createLabel({
		textAlign: "center",
		text: jsonData.user.friends_count,
		color: "#a01b1b",
		top: 230,
		width: 50,
		left: 25,
		zIndex: 999,
	})
	var vFriend = Titanium.UI.createLabel({
		textAlign: "center",
		text: jsonData.user.followers_count,
		color: "#a01b1b",
		top: 230,
		width: 50,
		left: 130,
		zIndex: 999,
	})
	var vPost = Titanium.UI.createLabel({
		textAlign: "center",
		text: jsonData.user.statuses_count,
		color: "#a01b1b",
		top: 230,
		width: 50,
		left: 230,
		zIndex: 999,
	})
			
	pRoot.add(vFollower);
	pRoot.add(vFriend);
	pRoot.add(vPost);
	
	pRoot.addEventListener('click', function(e){
		Ti.include('list.js');
		var wLi = new wList();
		wLi.lWeibo();
	})
			
}



var saveData = function(jsonData, pFile){

	var newDir = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, 'data');
	if(newDir){
		newDir.createDirectory();
	}
	Titanium.Filesystem.getFile(newDir.nativePath, pFile).write(jsonData);
		
}

var onData = function(pSection, pRoot, jData){
		
	//Ti.API.debug(jData[0].Home.content);	
		
	if(pSection == "home"){
		pRoot.top = 0;
		pRoot.data = homeList(pRoot, jData[0].Home.content);
	}
	if(pSection == 'images'){
		var jCoverflow = jData[1].Coverflow.content;
		var coverImagesData = [];
		var scrollImageData = [];
		
		for (var key in jCoverflow){
			coverImagesData.push({image:getCorrectFile(jCoverflow[key].img), width: 200, height: 280});
			var hImage = Titanium.UI.createImageView({
				image: getCorrectFile(jCoverflow[key].img),
				height: 480,
				width: 320,
			});
			scrollImageData.push(hImage);
		}
		pRoot.images = coverImagesData;
		
		pRoot.addEventListener('click', function(e){
			
			var heroImageWin = Titanium.UI.createWindow({
				width: 320,
			});
			heroImageWin.open();
			animateIt(heroImageWin, 'LIn');
			
			var scrollImageView = Titanium.UI.createScrollableView({
				height: 480,
				width: 320,
				top: 0,
				backgroundColor: 'transparent',
				currentPage: e.index,
				views: scrollImageData,
			});
			
			heroImageWin.add(scrollImageView);
			Ti.UI.iPhone.hideStatusBar();
			
			var barFunc = Titanium.UI.createView({
				backgroundColor: 'transparent',
				opacity: 0,
				top: 450,
				width: 320,
				height: 60,
				zindex: 99,
			});
			
			var btnBack = Titanium.UI.createButton({
				image: "media/nav/btn_back.png",
				top: 0,
				width: 54,
				height: 25,
				left: 15,
				
			})
			btnBack.addEventListener('click', function(e){
				Ti.UI.iPhone.showStatusBar();
				animateIt(heroImageWin, 'LOut');
			})
			barFunc.add(btnBack);
			
			var btnSave = Titanium.UI.createButton({
				image: "media/nav/btn_save.png",
				top: 0,
				width: 54,
				height: 25,
				left: 135,
				
			})			
			btnSave.addEventListener('click', function(e){
				
				Ti.API.debug(scrollImageView.toImage());
				Ti.Media.saveToPhotoGallery(scrollImageView.toImage(), {
			        success: function(e){
			          errorMSG("已保存到您的图库...");
			        },
			        error: function(e){
			           errorMSG("保存错误, 请稍后再试...");
			        }
			    });
				
			})
			barFunc.add(btnSave);
			
			var btnShare = Titanium.UI.createButton({
				image: "media/nav/btn_share.png",
				top: 0,
				width: 54,
				height: 25,
				right: 15,
			})			
			btnShare.addEventListener('click', function(e){
				Ti.UI.iPhone.showStatusBar();
				var shareArray = ['', '分享图片', scrollImageView.toImage(), ''];
				var hs = new hShare();
				hs.sinaShare(shareArray);
				Ti.UI.iPhone.hideStatusBar();
			})
			barFunc.add(btnShare);
			
			var hideBar = function(){
				barFunc.animate({opacity: 0, duration: 500});
			}				
			scrollImageView.addEventListener('click', function(e){
				setTimeout(hideBar, 5000);
				barFunc.animate({opacity: 1, duration: 500});
								
			});
			
			heroImageWin.add(barFunc);
			//TODO: if the images are landscape, then show the rotation of the windows
			//heroImageWin.orientationModes = [Ti.UI.LANDSCAPE_RIGHT];
			
			
		});
		
		
		
	}
	/*
	if(pSection == 'scrollImage'){
		var jCoverflow = jData[1].Coverflow;
		var scrollImageData = [];
		for (var key in jCoverflow){
			var hImage = Titanium.UI.createImageView({
				image: jCoverflow[key].img,
				height: 480,
				width: 320,
			});
			scrollImageData.push(hImage);
		}
		pRoot.views = scrollImageData;
		
	}
	*/
	
	if(pSection == "video"){
		pRoot.top = 0;
		pRoot.data = videoList(pRoot, jData[2].Video.content);
	}
	
	if(pSection == 'more'){
		var jMore = jData[4].More.content;
		pRoot.image = getCorrectFile(jMore.img);
	}
	
}

var offData = function(){
	
	var dataFile = Titanium.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'data/data.js');
	var tmpFile = Titanium.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'data/data.js');

	if(dataFile.exists()){
		var jData = JSON.parse(dataFile.read().text);
		
	}else{
		
		saveData(tmpFile.read().text, 'data.js');
		var jData = JSON.parse(tmpFile.read().text);
		
	}

	return jData;
}
